package com.coai.rtc.service

import com.coai.rtc.model.Call
import com.coai.rtc.model.CallParticipant
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service

/**
 * RTC事件服务 - 发布业务事件到Kafka
 * 用于数字孪生数据跟踪
 */
@Service
class RtcEventService(
    private val kafkaTemplate: KafkaTemplate<String, Any>
) {
    
    companion object {
        private const val TOPIC_RTC_EVENTS = "rtc-events"
    }
    
    /**
     * 发布通话发起事件
     */
    fun publishCallInitiated(call: Call) {
        val event = mapOf(
            "eventType" to "CALL_INITIATED",
            "callId" to call.id,
            "callType" to call.callType.name,
            "mediaType" to call.mediaType.name,
            "callerId" to call.callerId,
            "conversationId" to call.conversationId,
            "timestamp" to call.createdAt.toString()
        )
        
        kafkaTemplate.send(TOPIC_RTC_EVENTS, call.id, event)
    }
    
    /**
     * 发布参与者加入事件
     */
    fun publishParticipantJoined(call: Call, participant: CallParticipant) {
        val event = mapOf(
            "eventType" to "PARTICIPANT_JOINED",
            "callId" to call.id,
            "userId" to participant.userId,
            "joinedAt" to participant.joinedAt.toString(),
            "timestamp" to System.currentTimeMillis()
        )
        
        kafkaTemplate.send(TOPIC_RTC_EVENTS, call.id, event)
    }
    
    /**
     * 发布通话结束事件
     */
    fun publishCallEnded(call: Call) {
        val event = mapOf(
            "eventType" to "CALL_ENDED",
            "callId" to call.id,
            "duration" to (call.duration ?: 0),
            "startTime" to call.startTime.toString(),
            "endTime" to call.endTime.toString(),
            "timestamp" to System.currentTimeMillis()
        )
        
        kafkaTemplate.send(TOPIC_RTC_EVENTS, call.id, event)
    }
}
